package com.chy.utilsdemo.zip.zip;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 功能：
 * <p>
 * ──────────────────────────────────────────
 * version  变更日期       修改人    修改说明
 * ------------------------------------------
 * V1.0.0   2022/1/20     CHY     初版
 * ──────────────────────────────────────────
 */
public class ZipTest {
    public static void main(String[] args) {
        ZipTest zipTest = new ZipTest();
        try {
            //压缩
            zipTest.zip("D:\\zipfile\\hello.zip",new File("D:\\zipfile"));
            System.out.println("压缩完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件
     *
     * @param zipFilePath 压缩文件的路径
     * @param inputFile   被压缩的文件或路径
     * @throws Exception
     */
    private void zip(String zipFilePath, File inputFile) throws Exception {

        //创建ZipOutputStrem对象
        ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
        //调用方法
        zip(outputStream, inputFile, "");
        System.out.println("压缩中......");
        //关闭流
        outputStream.close();
    }

    private void zip(ZipOutputStream outputStream, File file, String base) throws IOException {
        //判断当前文件是否为目录
        if (file.isDirectory()) {
            //若当前文件为目录，则获取路径数组
            File[] files = file.listFiles();
            outputStream.putNextEntry(new ZipEntry(base + "/"));

            //判断参数是否为为空
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < files.length; i++) {
                zip(outputStream, files[i], base + files[i]);
            }
        } else {
            outputStream.putNextEntry(new ZipEntry(file.getName()));
            FileInputStream fileInputStream = new FileInputStream(file);
            int len;
            System.out.println(base);
            //判断是否到达流的尾部
            while ((len = fileInputStream.read()) != -1) {
                //将当前字节写入当前Zip条目
                outputStream.write(len);
            }
            fileInputStream.close();

        }
    }
}
